import L from 'leaflet'
import axios from 'axios'

L.PositionMarker = L.Marker.extend({
  options: {
    interactive: false
  },
  initialize: function(latlng, options) {
    options = options || {}
    options.icon = new L.Icon({
      iconUrl:
        '',
      iconSize: [36, 36],
      iconAnchor: [18, 18]
    })
    L.Marker.prototype.initialize.call(this, latlng, options)
  },
  onAdd: function(map) {
    L.Marker.prototype.onAdd.call(this, map)
    this.flashCount = 0
    this._startFlash()
  },
  onRemove: function(map) {
    L.Marker.prototype.onRemove.call(this, map)
    this._removed = true
    this._stopFlash()
  },
  _startFlash: function() {
    const that = this
    const flashFunc = function() {
      if (that._removed || that.flashCount > 3) {
        that._map.removeLayer(that)
        return
      }
      const icon = that.options.icon
      const { iconSize } = icon.options
      that.flashCount += iconSize[0] <= 24 ? 1 : 0
      const size = iconSize[0] <= 24 ? 36 : iconSize[0] - 4
      icon.options.iconSize = [size, size]
      icon.options.iconAnchor = [size / 2, size / 2]
      that.setIcon(icon)

      that._flashTimer = window.setTimeout(flashFunc, 150)
    }
    this._flashTimer = window.setTimeout(flashFunc, 150)
  },
  _stopFlash: function() {
    if (!this._flashTimer) {
      return
    }
    window.clearTimeout(this._flashTimer)
  }
})

const Position = {
  _positionMarker: null,
  _geoDics: {},
  geoCode: address => {
    return new Promise((resolve, reject) => {
      var request = axios.create({ timeout: 6000 })
      request({
        url: 'https://restapi.amap.com/v3/geocode/geo',
        method: 'get',
        params: { key: '6e7239cd1f1aaf595bca3753a67986f8', address }
      })
        .then(rep => {
          var lnglat = rep.data.geocodes[0].location.split(',')
          resolve(lnglat.reverse())
        })
        .catch(error => {
          reject(error)
        })
        .finally(() => {})
    })
  },
  setCenterView: async function(map, center, zoom) {
    var latLngArr = center.length > 1 ? center : this._geoDics[center]
    if (center.length === 1 && !latLngArr) {
      // 城市名需转换
      latLngArr = await this.geoCode(center[0]).catch(error => {
        console.log(error)
        center = [26.07467, 119.30946]
      })
      this._geoDics[center] = latLngArr
    }

    var latLng = L.latLng(latLngArr)
    map._onResize() // 路由转换时候导致地图不完整的bug——个别浏览器出现
    map.setView(latLng, zoom || 12)
  },
  startPosition: function(map, positionLatLng, zoom) {
    const latLng = L.latLng(positionLatLng)
    setTimeout(() => {
      map._onResize() // 路由转换时候导致地图不完整的bug——个别浏览器出现
      map.setView(latLng, zoom || 12)

      Position.closePosition(map)

      this._positionMarker = new L.PositionMarker(latLng)
      map.addLayer(this._positionMarker)
    }, 150) // 延迟500毫秒是为了使路由转换完成
  },
  closePosition: function(map) {
    if (this._positionMarker) {
      map.removeLayer(this._positionMarker)
      delete this._positionMarker
    }
  }
}
export default Position
